#region --- License & Copyright Notice ---
/*
Copyright (c) 2005-2011 Jeevan James
All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion

using System;
using System.IO;
using System.Windows.Forms;

using CodeBits;

using Id3;
using Id3.Frames;

using PictureManager.Properties;

namespace PictureManager
{
    public partial class FrmMain : Form
    {
        private Mp3Stream _mp3;
        private Id3Tag _tag;

        public FrmMain()
        {
            InitializeComponent();
        }

        private void RefreshFiles()
        {
            lvFiles.Items.Clear();

            string[] files = Directory.GetFiles(ttxtDirectory.Text, "*.mp3", SearchOption.TopDirectoryOnly);
            if (files.Length == 0)
                return;

            lvFiles.BeginUpdate();
            try
            {
                foreach (string file in files)
                {
                    string filename = Path.GetFileNameWithoutExtension(file);
                    var item = new ListViewItem(filename);
                    using (var mp3 = new Mp3File(file))
                    {
                        Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2x);
                        if (tag == null)
                            item.Group = lvFiles.Groups["groupNoPictures"];
                        else
                            item.Group = tag.Pictures.Count == 0 ? lvFiles.Groups["groupNoPictures"] : lvFiles.Groups["groupHasPictures"];
                    }
                    lvFiles.Items.Add(item);
                }
            }
            finally
            {
                lvFiles.EndUpdate();
            }
        }

        private void RefreshPictures()
        {
            lvPictures.Items.Clear();
            picture.Image = null;

            if (_mp3 != null)
            {
                _mp3.Dispose();
                _mp3 = null;
            }

            if (lvFiles.SelectedItems.Count == 0)
                return;

            string file = Path.Combine(ttxtDirectory.Text, lvFiles.SelectedItems[0].Text + ".mp3");
            _mp3 = new Mp3File(file, Mp3Permissions.ReadWrite);
            _tag = _mp3.GetTag(Id3TagFamily.Version2x);
            if (_tag == null)
                return;

            if (_tag.Pictures.Count == 0)
                return;

            foreach (PictureFrame pictureFrame in _tag.Pictures)
            {
                var item = new ListViewItem(pictureFrame.PictureType.ToString());
                item.SubItems.Add(pictureFrame.MimeType);
                string sizeStr = ByteSizeFriendlyName.Build(pictureFrame.PictureData.Length, new FriendlyNameOptions {
                    DecimalPlaces = 2,
                    GroupDigits = true,
                    UnitDisplayMode = UnitDisplayMode.HideOnlyForBytes,
                });
                item.SubItems.Add(sizeStr);
                item.SubItems.Add(pictureFrame.EncodingType.ToString());
                item.SubItems.Add(pictureFrame.Description);
                item.Tag = pictureFrame;
                lvPictures.Items.Add(item);
            }
            if (lvPictures.Items.Count > 0)
                lvPictures.Items[0].Selected = true;
        }

        private void OnFormLoad(object sender, EventArgs e)
        {
            string lastDirectory = Settings.Default.LastDirectory;
            if (!string.IsNullOrEmpty(lastDirectory) && Directory.Exists(lastDirectory))
            {
                ttxtDirectory.Text = lastDirectory;
                RefreshFiles();
            }
        }

        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            Settings.Default.LastDirectory = ttxtDirectory.Text;
            Settings.Default.Save();
        }

        private void OnBrowseDirectoryClicked(object sender, EventArgs e)
        {
            dlgBrowseFolder.SelectedPath = ttxtDirectory.Text;
            if (dlgBrowseFolder.ShowDialog(this) == DialogResult.OK)
            {
                ttxtDirectory.Text = dlgBrowseFolder.SelectedPath;
                RefreshFiles();
            }
        }

        private void OnRefreshClicked(object sender, EventArgs e)
        {
            Refresh();
        }

        private void OnAddClicked(object sender, EventArgs e)
        {
            using (var dlgPictureDetails = new DlgPictureDetails())
            {
                if (dlgPictureDetails.ShowDialog(this) != DialogResult.OK)
                    return;
                if (_tag == null)
                    _tag = new Id3Tag();
                _tag.Pictures.Add(dlgPictureDetails.PictureFrame);
                _mp3.WriteTag(_tag, 2, 3, WriteConflictAction.Replace);
                RefreshPictures();
            }
        }

        private void OnEditClicked(object sender, EventArgs e)
        {
            if (lvPictures.SelectedItems.Count == 0)
                return;

            using (var dlgPictureDetails = new DlgPictureDetails())
            {
                dlgPictureDetails.PictureFrame = lvPictures.SelectedItems[0].Tag as PictureFrame;
                if (dlgPictureDetails.ShowDialog(this) != DialogResult.OK)
                    return;
                _mp3.WriteTag(_tag, WriteConflictAction.Replace);
                RefreshPictures();
            }
        }

        private void OnDeleteClicked(object sender, EventArgs e)
        {
            foreach (ListViewItem item in lvPictures.CheckedItems)
            {
                var pictureFrame = item.Tag as PictureFrame;
                //TODO: _tag.Frames.Remove(pictureFrame);
            }
            _mp3.WriteTag(_tag, WriteConflictAction.Replace);
            RefreshPictures();
        }

        private void OnSelectedFileIndexChanged(object sender, EventArgs e)
        {
            RefreshPictures();
        }

        private void OnSelectedPictureIndexChanged(object sender, EventArgs e)
        {
            picture.Image = null;

            if (lvPictures.SelectedItems.Count == 0)
                return;

            var pictureFrame = (PictureFrame)lvPictures.SelectedItems[0].Tag;
            picture.Image = pictureFrame.GetPicture();
        }
    }
}